package com.itboye.shop.category.store;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.shop.R;
import com.itboye.shop.base.BaseActivity;
import com.itboye.shop.bean.OrderBean;
import com.itboye.shop.net.ResultEntity;
import com.itboye.shop.presenter.ShopPresenter;
import com.itboye.shop.util.loadutil.Const;
import com.itboye.shop.util.loadutil.MAlert;
import com.itboye.shop.util.loadutil.SPUtils;

import java.util.Observable;
import java.util.Observer;


/**
 * 支付
 */
public class GoPayActivity extends BaseActivity implements Observer {

    ImageView back, img_yinhang_check, img_weixin_check, img_qianbao_check, img_zhifubao_check;
    TextView tvTitle, queren;
    private int payType = 1;//默认为1支付宝
    boolean isZFB = true, isYE, isWX;
    private int recLen = 11;

    TextView tv_time;
    private long time = 900;//倒计时
    Handler handler = new Handler();

    String sku_pkid;
    String count;
    String address_id;
    String type;
    String order_code;
//    private IWXAPI api;

//    DingDanPresenter dingDanPresenter;
//    DingDanPresenter dingDanPresenter01;
    String uid;
    OrderBean orderBean;
//    WeiXinPayBean weixinBean;
//    GoPayBean bean;
//    SysTemMessgelPresenter sysTemMessgelPresenter;

    public static String GOUWUINEXIT = "gouwu.end.exit";// 余额支付购物结束
    private ShopPresenter shopPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_go_pay);
        tvTitle.setText(R.string.quzhifu);
        shopPresenter=new ShopPresenter(this);
//        dingDanPresenter = new DingDanPresenter(this);
//        dingDanPresenter01=new DingDanPresenter(this);
//        sysTemMessgelPresenter=new SysTemMessgelPresenter(this);
        uid = (String) SPUtils.get(this, null, Const.ID, "");
        handler.postDelayed(runnable, 1000);

//        api = WXAPIFactory.createWXAPI(this, Const.APP_ID);
//        api.registerApp(Const.APP_ID);

        sku_pkid = getIntent().getStringExtra("sku_pkid");
        count = getIntent().getStringExtra("count");
        address_id = getIntent().getStringExtra("address_id");
        order_code=getIntent().getStringExtra("order_code");
        type=getIntent().getStringExtra("type");
        orderBean =(OrderBean)getIntent().getSerializableExtra("model");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.queren:
                switch (payType) {
                    case 1:
                        isZFB = true;
                        isYE = false;
                        isWX = false;
                        zhifubaoPay();
                        break;
                    case 2:
                        isZFB = false;
                        isYE = true;
                        isWX = false;
                        qianBaoPay();
                        break;
                    case 3:
                        isZFB = false;
                        isYE = false;
                        isWX = true;
                        weixinPay();
                        break;
                }
                break;
            case R.id.img_zhifubao_check:
                setPayTypeSelected(1);
                break;
            case R.id.img_qianbao_check:
                setPayTypeSelected(2);
                break;
            case R.id.img_weixin_check:
                setPayTypeSelected(3);
                break;
        }
    }

    /**
     * 支付宝支付
     */
    private void zhifubaoPay() {
//        if(type!=null){
            showProgressDialog("请稍后", true);

//            if(type.equals("one")){//判断是立即购买还是重新支付
////                dingDanPresenter.lijiGouMai(IsUtilUid.sId(),uid, sku_pkid, count, address_id, "");
//            }else if(type.equals("two")){//重新支付
////                dingDanPresenter.chongxinGouMai(IsUtilUid.sId(),uid,order_code);
//            }else if(type.equals("three")){//维修支付
//              //  sysTemMessgelPresenter.onZhiFu(uid,getIntent().getStringExtra("id"));
////                zfb(orderBean);
//            }
//        }
    }

    /**
     * 钱包支付
     */
    private void qianBaoPay() {
//        if(type!=null){
            showProgressDialog("请稍后", true);
            shopPresenter=new ShopPresenter(this);
            shopPresenter.payByWallet(uid,orderBean.getPay_code());
            if(type.equals("one")){//判断是立即购买还是重新支付
//                dingDanPresenter.lijiGouMai(IsUtilUid.sId(),uid, sku_pkid, count, address_id, "");
            }else if(type.equals("two")){//重新支付
//                dingDanPresenter.chongxinGouMai(IsUtilUid.sId(),uid,order_code);
            }else if(type.equals("three")){//维修支付
//                dingDanPresenter01.yueZhiFu(uid,orderBean.getPay_code());
            }
//        }
    }

    /**
     * 微信支付
     */
    private void weixinPay() {
        if(type!=null){
            showProgressDialog("请稍后", true);
            if(type.equals("one")){
//                dingDanPresenter.lijiGouMai(IsUtilUid.sId(),uid, sku_pkid, count, address_id, "");
            }else if(type.equals("two")){
//                dingDanPresenter.chongxinGouMai(IsUtilUid.sId(),uid,order_code);
            }else if(type.equals("three")){
              //  sysTemMessgelPresenter.onZhiFu(uid,getIntent().getStringExtra("id"));
//                dingDanPresenter.WeiXinPay(orderBean.getPay_code());
            }
        }
    }

    /**
     * @param type 支付方式的选中状态
     *             1、支付宝
     *             2、钱包
     *             3、微信
     */
    public void setPayTypeSelected(int type) {
        clearAllSelected();
        switch (type) {
            case 1:
                img_zhifubao_check.setBackgroundResource(R.drawable.pay_type_selected);
                break;
            case 2:
                img_qianbao_check.setBackgroundResource(R.drawable.pay_type_selected);
                break;
            case 3:
                img_weixin_check.setBackgroundResource(R.drawable.pay_type_selected);
                break;
        }
        payType = type;
    }

    public void clearAllSelected() {
        img_zhifubao_check.setBackgroundResource(R.drawable.pay_type_unselected);
        img_qianbao_check.setBackgroundResource(R.drawable.pay_type_unselected);
        img_weixin_check.setBackgroundResource(R.drawable.pay_type_unselected);
        img_yinhang_check.setBackgroundResource(R.drawable.pay_type_unselected);

    }


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            time--;
            tv_time.setText("" + formatLongToTimeStr(time));
            if (time > 0) {
                handler.postDelayed(this, 1000);
            }
        }
    };

    public String formatLongToTimeStr(Long l) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        second = l.intValue();
        if (second > 60) {
            minute = second / 60;
            second = second % 60;
        }

        if (minute > 60) {
            hour = minute / 60;
            minute = minute % 60;
        }
        String strtime = minute + ":" + second;
        return strtime;

    }


    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType()== ShopPresenter.payByWallet_success) {
                MAlert.alert(entity.getData());
                finish();
            }else if (entity.getEventType()== ShopPresenter.payByWallet_fail) {
                MAlert.alert(entity.getData());
            }
            //订单直接购买
//            if (entity.getEventType() == DingDanPresenter.liji_goumai_success) {
//                bean = (GoPayBean) entity.getData();
//                System.out.print("update");
//                if (isZFB) {
//                    System.out.print("isZFB");
//                    zfb(bean);
//                } else if (isWX) {
//                    dingDanPresenter.WeiXinPay(bean.getPay_code());
//                }else if(isYE){
//                    dingDanPresenter01.yueZhiFu(uid,bean.getPay_code());
//                }
//            }
//            if (entity.getEventType() == DingDanPresenter.liji_goumai_fail) {
//                bean = (GoPayBean) entity.getData();
//            }
//            //重新支付订单
//            if (entity.getEventType() == DingDanPresenter.chongxin_goumai_success) {
//                bean = (GoPayBean) entity.getData();
//                System.out.print("update");
//                if (isZFB) {
//                    System.out.print("isZFB");
//                    zfb(bean);
//                    ByAlert.alert("支付宝");
//                } else if (isWX) {
//                    dingDanPresenter.WeiXinPay(bean.getPay_code());
//                }else if(isYE){
//                    dingDanPresenter01.yueZhiFu(uid,bean.getPay_code());
//                }
//            }
//            if (entity.getEventType() == DingDanPresenter.chongxin_goumai_fail) {
//                bean = (GoPayBean) entity.getData();
//            }
//            //维修支付
//            if (entity.getEventType() == SysTemMessgelPresenter.zhifu_success) {
////                bean = (GoPayBean) entity.getData();
////                System.out.print("update");
////                if (isZFB) {
////                    System.out.print("isZFB");
////                    zfb(bean);
////                    ByAlert.alert("支付宝");
////                } else if (isWX) {
////                    dingDanPresenter.WeiXinPay(bean.getPay_code());
////                }else if(isYE){
////                    dingDanPresenter01.yueZhiFu(uid,bean.getPay_code());
////                }
//            }
//            if (entity.getEventType() == SysTemMessgelPresenter.zhifu_fail) {
//                bean = (GoPayBean) entity.getData();
//                if(type.equals("three")){
//                    dingDanPresenter.quxiaoZhifu(IsUtilUid.isUid(),getIntent().getStringExtra("id"));
//                }
//            }
//            //微信预支付
//            if (entity.getEventType() == DingDanPresenter.weixin_pay_success) {
//                weixinBean = (WeiXinPayBean) entity.getData();
//
//                PayReq req = new PayReq();
//                req.appId = Const.APP_ID;
//                req.partnerId = weixinBean.getPartnerid();
//                req.prepayId = weixinBean.getPrepayid();
//                req.nonceStr = weixinBean.getNoncestr();
//                req.timeStamp = weixinBean.getTimestamp();
//                req.packageValue = "Sign=WXPay";
//                req.sign = weixinBean.getSign();
//                boolean is = api.sendReq(req);
//                if (is) {
//                     ByAlert.alert("已调其成功");
//                    finish();
//                } else {
//                    ByAlert.alert("调起微信支付失败");
//                }
//            }
//            if (entity.getEventType() == DingDanPresenter.weixin_pay_fail) {
//                bean = (GoPayBean) entity.getData();
//                if(type.equals("three")){
//                    dingDanPresenter.quxiaoZhifu(IsUtilUid.isUid(),getIntent().getStringExtra("id"));
//                }
//            }
//            //余额支付
//            if (entity.getEventType() == DingDanPresenter.yue_success) {
//                ByAlert.alert(entity.getData());
//                finish();
//                // 发送广播通知LoginActivity结束
//                Intent intent1 = new Intent(GOUWUINEXIT);
//                sendBroadcast(intent1);
//            }
//            if (entity.getEventType() == DingDanPresenter.yue_fail) {
//               ByAlert.alert(entity.getData());
//                if(type.equals("three")){
//                    dingDanPresenter.quxiaoZhifu(IsUtilUid.isUid(),getIntent().getStringExtra("id"));
//                }
//            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }
    /** 支付宝支付业务：入参app_id */
    public static final String APPID = "2016122704665497";

    /** 支付宝账户登录授权业务：入参pid值 */
    public static final String PID = "2088221666614017";
    /** 支付宝账户登录授权业务：入参target_id值 */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    public static final String RSA_PRIVATE="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsNiOkk2F22n5WgY/6qUhMFSLU03IB4OSpOzB3/kTXRQUvQVRCmikKLTlRQgHPbQfdUrRycIWK3+GDeXfqK7mr9Nb8KZzpjNteCdD1z+TA/xbcHumPd4v3Z7pcYdoFGdVmvyxUDcnn1DUHlDHeEKez3CSGl1zHUIyKYW0ypEX5BNL4KWC/rch/Ycr9mQhp+83vml7ccLBL22LD6MUyp8h0x2JYEouaJQ4ptNagZdt3FOiGIptTJm5FjHUw9Dy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Ahk3HfDhNENIbr18cvtyhoKu9YwkTxWtO/sZTgxuD3VRWDdgv/AI2rDAoGAFSj4/5YC1SwOZnVqMdA69wJUxEyBBWpwBU2Gln3IgggtVIkbLYk7P5PwWgTmShz0NmQgCKon0Eu8M1AI3fbZJUAAZdtnqHgJ+9synjqnsOTXdRKmCcaS9s/W3pVrQ6yEsCN2vK+7gMQN2MhKJTO5IYQmUyVWRh2+a5n3i41fwps=";

    private static final int SDK_PAY_FLAG = 1;

    /**
     * 支付宝
     */
//    private void zfb(GoPayBean bean){
//        /**
//         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
//         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
//         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
//         * orderInfo的获取必须来自服务端；
//         */
//        String money=bean.getPay_money();
//        double m= Double.parseDouble(money)/100;
//        String content=bean.getPay_code();
//        String code=bean.getPay_code();
//        String time=bean.getCreate_time();
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID,m+"",content,code,time);
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//        String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE);
//        final String orderInfo = orderParam + "&" + sign;
//
//
//
////        Runnable payRunnable = new Runnable() {
////
////            @Override
////            public void run() {
////                PayTask alipay = new PayTask(GoPayActivity.this);
////                Map<String, String> result = alipay.payV2(orderInfo, true);
////
////                Message msg = new Message();
////                msg.what = SDK_PAY_FLAG;
////                msg.obj = result;
////                mHandler.sendMessage(msg);
////            }
////        };
//
////        Thread payThread = new Thread(payRunnable);
////        payThread.start();
//    }

//    private Handler mHandler = new Handler() {
//        @SuppressWarnings("unused")
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case SDK_PAY_FLAG: {
//
//                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
//                    /**
//                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
//                     */
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
//                    String resultStatus = payResult.getResultStatus();
//                    // 判断resultStatus 为9000则代表支付成功
//                    if (TextUtils.equals(resultStatus, "9000")) {
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(GoPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
//                        finish();
//                    } else {
//                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        Toast.makeText(GoPayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
//                    }
//                    break;
//                }
//
//                default:
//                    break;
//            }
//        };
//    };
}
